﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Data;
using UFC.DBUtility;
using System.Xml;
using UFC.Common;

namespace MESQualityHistoryRecord
{
    public class SendApsAndReportToQMS
    {
        private const string qms_apsInfoSend = "qms_apsInfoSend";//排产下发后
        private const string qms_report = "qms_report";//工序完工
        public void Excute()
        {
            //推送排产下发数据(apsplandetail表触发器)
            //sendApsInfoToQMS();
            //报工数据()
            //sendReportInfoToQMS();
            //新QMS理化委托调旧QMS接口
            //RunSubmitIqsOrderByNewQmsToOldQms();
            //推送理化委托结果给新QMS
            //sendIqsOrderResultToQMS();
            //生产批次
            //sendContainerInfoToQms();
            //退料退库检验申请
            sendStockReturnApplyDataToQMS();
        }

        #region 推送排产下发数据
        /// <summary>
        /// 推送排产下发数据
        /// </summary>
        private void sendApsInfoToQMS()
        {
            DataTable apsDT = getApsInfoSend();
            DataView dv = apsDT.AsDataView();
            DataTable dt = dv.ToTable(true, "containerid", "mfgordername", "heat_batch", "workflowid", "workflowtype", "workflowname", "workflowrevision", "process_no",
                                    "productname", "productrevision", "productdescription", "containername", "qty", "childcontainerno", "containertype", "familylistnames");
            foreach (DataRow row in dt.Rows)
            {
                DataView dv2 = apsDT.AsDataView();
                dv2.RowFilter = "containerid='" + row["containerid"] + "'";
                DataTable wsDt = dv2.ToTable(true, "specno", "specname", "specrevision", "teamname", "starttime", "endtime");
                string stepIds = string.Join(",", dv2.ToTable(true, "workflowstepid").AsEnumerable().Select(r => r.Field<string>("workflowstepid")));
                string strXml = createApsInfoXml(row, wsDt);
                try
                {
                    //调用QMS接口
                    LogHelp.WriteLog("推送QMS排产下发数据：" + strXml);
                    QISWebServices.IQIS460_MES_PRODTASK qis = new QISWebServices.IQIS460_MES_PRODTASK();
                    var result = qis.MES_TO_QIS_PROD(strXml);
                    //var result = @"<?xml version='1.0' encoding='UTF-8'?><RESULTs><RESULT><task_id>任务id</task_id><type>failure</type><reason>异常信息</reason></RESULT></RESULTs>";//接口返回结果;
                    LogHelp.WriteLog("推送QMS排产下发数据-返回信息：" + result);
                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(result);
                    var type = doc.SelectSingleNode("RESULTs/RESULT/type").InnerText;
                    //记录日志表
                    Dictionary<string, string> recordPara = new Dictionary<string, string>() { 
                         {"ParentId",""},{"RecordType",qms_apsInfoSend},
                        {"SendXml",strXml},{"ResXml",result},{"IsSuccess",type.Equals("failure")?"1":"0"},{"ContainerID",row["ContainerID"].ToString()},{"ContainerName",row["ContainerName"].ToString()},{"ProductName",row["ProductName"].ToString()},{"WorkflowStepName",""}};
                    OracleDAL.InserOtherSystemRecord(recordPara);
                }
                catch (Exception ex)
                {
                    LogHelp.WriteError("推送QMS排产下发数据异常", ex);
                    //记录日志表
                    Dictionary<string, string> recordPara = new Dictionary<string, string>() { 
                         {"ParentId",""},{"RecordType",qms_apsInfoSend},
                        {"SendXml",strXml},{"ResXml",ex.Message +ex.StackTrace},{"IsSuccess","1"},{"ContainerID",row["ContainerID"].ToString()},{"ContainerName",row["ContainerName"].ToString()},{"ProductName",row["ProductName"].ToString()},{"WorkflowStepName",""}};
                    OracleDAL.InserOtherSystemRecord(recordPara);
                }
                finally
                {
                    //更新sendtoothersystemdata表
                    OracleHelper.ExecuteSql(string.Format(@"update sendtoothersystemdatadetail sdd set sdd.lastchangedate=sysdate,sdd.issend='1' 
                    where sdd.sendtype='{0}' and sdd.issend='0' and sdd.sendtoothersystemdataid in (
                    select sd.id from sendtoothersystemdata sd where sd.containerid='{1}' and sd.workflowstepid in ('{2}')
                    )", qms_apsInfoSend, row["ContainerID"].ToString(), stepIds.Replace(",", "','")));
                }
            }

        }
        /// <summary>
        /// 查询排产下发数据
        /// </summary>
        /// <returns></returns>
        private DataTable getApsInfoSend()
        {
            string strSql = @"select * from (select sd.containerid,m.mfgordername,u.attributevalue heat_batch,w.workflowtype,wb.workflowname,w.workflowrevision,w.process_no,
                    cci.productname,cci.productrevision,cci.productdescription,cci.containername,cci.qty, 
                    w.workflowid,sd.workflowstepid,s.specno,sb2.specname,s.specrevision,t.teamname,
                    to_char(al.starttime,'yyyy-MM-dd hh24:mi:ss') starttime,to_char(al.endtime,'yyyy-MM-dd hh24:mi:ss') endtime,sd.createdate,
                    case when cci.containertype=3 then (select to_char(wm_concat(substr(c.containername,instr(c.containername,'/')+1))) childcontainerno
       						                    from container c where c.parentcontainerid=sd.containerid) 
                         when cci.containertype=7 then cci.realcontainerno 
                         else '' end childcontainerno,
                    decode(cci.containertype,2,'批量加工',3,'批量带子序号',7,'单件加工','未知') containertype,cci.familylistnames 
                    from sendtoothersystemdata sd
                    inner join sendtoothersystemdatadetail sdd on sdd.sendtoothersystemdataid=sd.id
                    inner join apsplandetail al on al.apsplandetailid=sd.parentid
                    left join containercurrentinfo cci on cci.containerid=al.containerid
                    left join mfgorder m on m.mfgorderid=cci.mfgorderid
                    left join userattribute u on u.parentid =sd.containerid  and u.userattributename='熔炉号'
                    left join workflowstep ws on ws.workflowstepid =sd.workflowstepid
                    left join workflow w on w.workflowid =ws.workflowid 
                    left join workflowbase wb on wb.workflowbaseid =w.workflowbaseid 
                    left join specbase sb on sb.specbaseid=ws.specbaseid
                    left join spec s on s.specid=nvl(sb.revofrcdid,ws.specid)
                    left join specbase sb2 on sb2.specbaseid =s.specbaseid 
                    left join team t on t.teamid=al.teamid
                    where sdd.sendtype='" + qms_apsInfoSend + "' and sdd.issend=0 order by sd.createdate) where rownum<500";
            return OracleHelper.QueryTable(strSql, null);
        }
        /// <summary>
        /// 生成ApsXML
        /// </summary>
        /// <param name="dr"></param>
        /// <param name="wsdt"></param>
        /// <returns></returns>
        private string createApsInfoXml(DataRow dr, DataTable wsdt)
        {
            XmlDocument doc = new XmlDocument();
            doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", ""));
            XmlNode ProdsNode = doc.CreateElement("QIS_PRODs");
            XmlNode ProdNode = doc.CreateElement("QIS_PROD");

            #region QIS_PROD
            XmlNode node = doc.CreateElement("task_id");//任务id
            node.AppendChild(doc.CreateCDataSection(dr["containerid"].ToString()));
            ProdNode.AppendChild(node);

            node = doc.CreateElement("order_no");//订单编号
            node.AppendChild(doc.CreateCDataSection(dr["mfgordername"].ToString()));
            ProdNode.AppendChild(node);

            node = doc.CreateElement("if_pecu");//是否特种工艺
            node.AppendChild(doc.CreateCDataSection(dr["workflowtype"].ToString().Contains("特种") ? "是" : "否"));
            ProdNode.AppendChild(node);

            node = doc.CreateElement("production_type");//生产类型
            node.AppendChild(doc.CreateCDataSection("生产")); //dr["task_id"].ToString();
            ProdNode.AppendChild(node);

            node = doc.CreateElement("heat_batch");//炉批号
            node.AppendChild(doc.CreateCDataSection(dr["heat_batch"].ToString()));
            ProdNode.AppendChild(node);

            node = doc.CreateElement("rourion_code");//工艺编号
            node.AppendChild(doc.CreateCDataSection(dr["process_no"].ToString()));
            ProdNode.AppendChild(node);

            node = doc.CreateElement("rourion_chart_code");//工艺版本号
            node.AppendChild(doc.CreateCDataSection(dr["workflowrevision"].ToString()));
            ProdNode.AppendChild(node);

            node = doc.CreateElement("workflowid");//工艺ID
            node.AppendChild(doc.CreateCDataSection(dr["workflowid"].ToString()));
            ProdNode.AppendChild(node);

            node = doc.CreateElement("model");//机型
            node.AppendChild(doc.CreateCDataSection(dr["familylistnames"].ToString()));
            ProdNode.AppendChild(node);

            node = doc.CreateElement("flowcard_type");//流卡类型
            node.AppendChild(doc.CreateCDataSection(dr["containertype"].ToString()));
            ProdNode.AppendChild(node);

            XmlNode ProductsNode = doc.CreateElement("PRODUCTs");
            XmlNode ProductNode = doc.CreateElement("PRODUCT");
            XmlNode node2 = doc.CreateElement("product_code");//产品件号
            node2.AppendChild(doc.CreateCDataSection(dr["productname"].ToString()));
            ProductNode.AppendChild(node2);

            node2 = doc.CreateElement("product_chart_code");//产品版本号
            node2.AppendChild(doc.CreateCDataSection(dr["productrevision"].ToString()));
            ProductNode.AppendChild(node2);

            node2 = doc.CreateElement("product_name");//产品名称
            node2.AppendChild(doc.CreateCDataSection(dr["productdescription"].ToString()));
            ProductNode.AppendChild(node2);

            node2 = doc.CreateElement("product_batch");//批次号
            node2.AppendChild(doc.CreateCDataSection(dr["containername"].ToString()));
            ProductNode.AppendChild(node2);

            node2 = doc.CreateElement("product_num");//数量
            node2.AppendChild(doc.CreateCDataSection(dr["qty"].ToString()));
            ProductNode.AppendChild(node2);

            node2 = doc.CreateElement("product_no");//产品编号------
            node2.AppendChild(doc.CreateCDataSection(dr["childcontainerno"].ToString()));
            ProductNode.AppendChild(node2);
            ProductsNode.AppendChild(ProductNode);


            XmlNode ProceduresNode = doc.CreateElement("PROCEDUREs");
            foreach (DataRow row in wsdt.Rows)
            {
                XmlNode ProcedureNode = doc.CreateElement("PROCEDURE");
                XmlNode node3 = doc.CreateElement("procedure_code");//工序号
                node3.AppendChild(doc.CreateCDataSection(row["specno"].ToString()));
                ProcedureNode.AppendChild(node3);

                node3 = doc.CreateElement("procedure_name");//工序名称
                node3.AppendChild(doc.CreateCDataSection(row["specname"].ToString()));
                ProcedureNode.AppendChild(node3);

                node3 = doc.CreateElement("proecedure_version");//工序版本号
                node3.AppendChild(doc.CreateCDataSection(row["specrevision"].ToString()));
                ProcedureNode.AppendChild(node3);

                node3 = doc.CreateElement("production_dept_name");//计划生产单位名称(班组)
                node3.AppendChild(doc.CreateCDataSection(row["teamname"].ToString()));
                ProcedureNode.AppendChild(node3);

                node3 = doc.CreateElement("start_time");//工序生产计划开始时间
                node3.AppendChild(doc.CreateCDataSection(row["starttime"].ToString()));
                ProcedureNode.AppendChild(node3);

                node3 = doc.CreateElement("end_time");//工序生产计划完成时间
                node3.AppendChild(doc.CreateCDataSection(row["endtime"].ToString()));
                ProcedureNode.AppendChild(node3);
                ProceduresNode.AppendChild(ProcedureNode);
            }
            #endregion
            ProdNode.AppendChild(ProductsNode);
            ProdNode.AppendChild(ProceduresNode);
            ProdsNode.AppendChild(ProdNode);
            doc.AppendChild(ProdsNode);
            return doc.InnerXml;
        }

        #endregion

        #region 报工数据
        /// <summary>
        /// 报工数据
        /// </summary>
        private void sendReportInfoToQMS()
        {
            DataTable dt = getReportInfo();
            if (dt.Rows.Count == 0) { return; }
            foreach (DataRow dr in dt.Rows)
            {
                string strXml = createReportInfoXml(dr);
                //DataView dv = dt.AsDataView();
                string containerIds = dr["containerid"].ToString(); //string.Join(",", dv.ToTable(true, "containerid").AsEnumerable().Select(r => r.Field<string>("containerid")));
                string stepIds = dr["workflowstepid"].ToString();// string.Join(",", dv.ToTable(true, "workflowstepid").AsEnumerable().Select(r => r.Field<string>("workflowstepid")));
                try
                {
                    //调用QMS接口
                    LogHelp.WriteLog("推送QMS工序检验数据：" + strXml);
                    QISWebServices.IQIS460_MES_PRODTASK qis = new QISWebServices.IQIS460_MES_PRODTASK();
                    var result = qis.MES_TO_QIS_PROCESS(strXml);
                    //var result = @"<?xml version='1.0' encoding='UTF-8'?><RESULTs><RESULT><task_id>任务id</task_id><type>failure</type><reason>异常信息</reason></RESULT></RESULTs>";//接口返回结果;
                    LogHelp.WriteLog("推送QMS工序检验数据-返回信息：" + result);
                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(result);
                    var type = doc.SelectSingleNode("RESULTs/RESULT/type").InnerText;
                    //记录日志表
                    Dictionary<string, string> recordPara = new Dictionary<string, string>() { 
                         {"ParentId",""},{"RecordType",qms_report},
                         {"SendXml",strXml},{"ResXml",result},{"IsSuccess",type.Equals("failure")?"1":"0"},{"ContainerID",""},{"ContainerName",""},{"ProductName",""},{"WorkflowStepName",""}};
                    OracleDAL.InserOtherSystemRecord(recordPara);
                }
                catch (Exception ex)
                {
                    LogHelp.WriteError("推送QMS工序检验数据异常", ex);
                    //记录日志表
                    Dictionary<string, string> recordPara = new Dictionary<string, string>() { 
                         {"ParentId",""},{"RecordType",qms_report},
                         {"SendXml",strXml},{"ResXml",ex.Message +ex.StackTrace},{"IsSuccess","1"},{"ContainerID",""},{"ContainerName",""},{"ProductName",""},{"WorkflowStepName",""}};
                    OracleDAL.InserOtherSystemRecord(recordPara);
                }
                finally
                {
                    //更新sendtoothersystemdata表
                    OracleHelper.ExecuteSql(string.Format(@"update sendtoothersystemdatadetail sdd set sdd.lastchangedate=sysdate,sdd.issend='1' 
                    where sdd.sendtype='{0}' and sdd.issend='0' and sdd.sendtoothersystemdataid in (
                    select sd.id from sendtoothersystemdata sd where sd.containerid IN('{1}') and sd.workflowstepid in ('{2}')
                    )", qms_report, containerIds.Replace(",", "','"), stepIds.Replace(",", "','")));
                }
            }
        }

        private DataTable getReportInfo()
        {
            string strSql = @"select * from (select sd.containerid, m.mfgordername,cci.productname,cci.productrevision,cci.productdescription,c.containerstepworkreportid,
                            cci.containername,decode(cci.containertype,2,'批量加工',3,'批量带子序号',7,'单件加工','未知') containertype,
                            cci.qty,c.qty check_num,wb.workflowname,w.workflowrevision,w.process_no,e.fullname,e.employeename,
                            t.teamname,wc.workcentername,f.factoryname,sd.workflowstepid,s.specno,sb2.specname,s.specrevision,c.createdate enddate,sd.createdate,
                            case when cci.containertype=3 then (select to_char(wm_concat(substr(c.containername,instr(c.containername,'/')+1))) childcontainerno
       						                from container c where c.parentcontainerid=sd.containerid) 
                                 when cci.containertype=7 then cci.realcontainerno 
                                 else '' end childcontainerno,
                            case when cci.containertype=3 then (select to_char(wm_concat(c.containerid)) childcontainerid
       						                from container c where c.parentcontainerid=sd.containerid) 
                                 when cci.containertype=7 then cci.containerid 
                                 else '' end childcontainerid,
                            stb.stepinfoname,st.stepno,c.isuse,cd.recvdate startdate,c.checktype
                            from (select sd.* from sendtoothersystemdata sd
                            inner join sendtoothersystemdatadetail sdd on sdd.sendtoothersystemdataid=sd.id where sdd.sendtype='qms_report' and sdd.issend=0) sd
                            left join containerstepworkreport c on c.containerid =sd.containerid and c.workflowstepid =sd.workflowstepid
                            left join containercurrentinfo cci on cci.containerid=sd.containerid
                            left join containerstepdispatch cd on cd.containerstepdispatchid =c.containerstepdispatchid 
                            left join mfgorder m on m.mfgorderid=cci.mfgorderid
                            left join employee e on e.employeeid =c.workerid 
                            left join team t on t.teamid=c.teamid 
                            left join workcenter wc on wc.workcenterid =c.workcenterid
                            left join factory f on f.factoryid =c.factoryid 
                            left join workflowstep ws on ws.workflowstepid =sd.workflowstepid
                            left join workflow w on w.workflowid =ws.workflowid 
                            left join workflowbase wb on wb.workflowbaseid =w.workflowbaseid 
                            left join specbase sb on sb.specbaseid=ws.specbaseid
                            left join spec s on s.specid=nvl(sb.revofrcdid,ws.specid)
                            left join specbase sb2 on sb2.specbaseid =s.specbaseid
                            left join stepinfo st on st.stepinfoid =c.stepinfoid 
                            left join stepinfobase stb on stb.stepinfobaseid =st.stepinfobaseid  
                            where 1=1 and c.isuse=0 order by sd.createdate desc) where rownum<500";
            return OracleHelper.QueryTable(strSql, null);
        }

        private string createReportInfoXml(DataRow dr)
        {
            XmlDocument doc = new XmlDocument();
            doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", ""));
            XmlNode ProcesssNode = doc.CreateElement("QIS_PROCESSs");
            XmlNode nodeT = doc.CreateElement("TASK_TYPE");//任务类型
            nodeT.InnerText = "工序检验";
            ProcesssNode.AppendChild(nodeT);
            //foreach (DataRow dr in dt.Rows)
            //{
            XmlNode ProcessNode = doc.CreateElement("QIS_PROCESS");
            XmlNode node = doc.CreateElement("TASK_ID");//任务id
            node.AppendChild(doc.CreateCDataSection(dr["containerid"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("ORDER_NO");//订单编号
            node.AppendChild(doc.CreateCDataSection(dr["mfgordername"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("PRODUCT_CODE");//产品件号
            node.AppendChild(doc.CreateCDataSection(dr["productname"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("PRODUCT_NAME");//产品名称
            node.AppendChild(doc.CreateCDataSection(dr["productdescription"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("PRODUCT_CHART_CODE");//产品版本号
            node.AppendChild(doc.CreateCDataSection(dr["productrevision"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("PROCESS_TASK_ID");//工序任务id
            node.AppendChild(doc.CreateCDataSection(dr["containerstepworkreportid"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("PRODUCT_BATCH");//批次号
            node.AppendChild(doc.CreateCDataSection(dr["containername"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("BATCH_TYPE");//批次类型(数量批/序号批/单件单卡)
            node.AppendChild(doc.CreateCDataSection(dr["containertype"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("SUPPLIER");//供应商
            node.AppendChild(doc.CreateCDataSection("供应商"));//dr["supplier"].ToString();
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("CHECK_NUM");//交检数量
            node.AppendChild(doc.CreateCDataSection(dr["check_num"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("BATCH_ID");//批次ID
            node.AppendChild(doc.CreateCDataSection(dr["containerid"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("PROCESS_ID");//工序ID
            node.AppendChild(doc.CreateCDataSection(dr["workflowstepid"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("OPER_CODE");//操作人员编号
            node.AppendChild(doc.CreateCDataSection(dr["employeename"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("OPER_NAME");//操作人名称
            node.AppendChild(doc.CreateCDataSection(dr["fullname"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("REPORT_WORKGROUP");//报工班组
            node.AppendChild(doc.CreateCDataSection(dr["teamname"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("REPORT_DEPT");//报工车间
            node.AppendChild(doc.CreateCDataSection(dr["workcentername"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("BATCH_NUM");//批次数量
            node.AppendChild(doc.CreateCDataSection(dr["qty"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("ROURION_CODE");//工艺编号
            node.AppendChild(doc.CreateCDataSection(dr["process_no"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("ROURION_CHART_CODE");//工艺版本号
            node.AppendChild(doc.CreateCDataSection(dr["workflowrevision"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("PROCEDURE_NO");//工序号
            node.AppendChild(doc.CreateCDataSection(dr["specno"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("PROCEDURE_NAME");//工序名称
            node.AppendChild(doc.CreateCDataSection(dr["specname"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("PROECEDURE_VERSION");//工序版本号
            node.AppendChild(doc.CreateCDataSection(dr["specrevision"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("STEP_CODE");//工步号
            node.AppendChild(doc.CreateCDataSection(dr["stepno"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("STEP_NAME");//工步名称
            node.AppendChild(doc.CreateCDataSection(dr["stepinfoname"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("PRODUCTION_DEPT_NAME");//生产单位
            node.AppendChild(doc.CreateCDataSection(dr["factoryname"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("START_DATE");//工序任务开始时间
            node.AppendChild(doc.CreateCDataSection(dr["startDate"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("END_DATE");//工序任务完工时间
            node.AppendChild(doc.CreateCDataSection(dr["endDate"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("CHECK_TYPE");//检验类型
            node.AppendChild(doc.CreateCDataSection(dr["checkType"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("RUN_STATE");//执行状态
            node.AppendChild(doc.CreateCDataSection(dr["isuse"].ToString().Equals("0") ? "新增" : (dr["isuse"].ToString().Equals("1") ? "撤销" : "未知")));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("PRODUCT_NO");//产品编号
            node.AppendChild(doc.CreateCDataSection(dr["childcontainerno"].ToString()));
            ProcessNode.AppendChild(node);
            //子序号检测项工人检验结果
            if (!string.IsNullOrWhiteSpace(dr["childcontainerno"].ToString()))
            {
                foreach (var containerid in dr["childcontainerid"].ToString().Split(','))
                {
                    var containerno = OracleHelper.GetSingle(string.Format(@"select substr(c.containername,instr(c.containername,'/')+1) realcontainerno from container c where containerid='{0}'", containerid));
                    var stepcheckpointResult = @"select s.bubblenumber,sr.workcheckpointresultnotedis
                            from stepcheckpoint s 
                            left join stepcheckpointresult sr on sr.stepcheckpointid =s.stepcheckpointid and sr.containerid='{0}'
                            where s.workflowstepid ='{1}' order by s.bubblenumber";
                    DataTable stepcheckpointDt = OracleHelper.QueryTable(string.Format(stepcheckpointResult, containerid, dr["workflowstepid"].ToString()), null);
                    //检测项及录入结果数据
                    if (stepcheckpointDt.Rows.Count > 0)
                    {
                        foreach (DataRow dr2 in stepcheckpointDt.Rows)
                        {
                            XmlNode ListNode = doc.CreateElement("LIST");
                            XmlNode node2 = doc.CreateElement("PRODUCT_NO");//产品编号(子序号)
                            node2.AppendChild(doc.CreateCDataSection(containerno.ToString()));
                            ListNode.AppendChild(node2);
                            node2 = doc.CreateElement("BUBBLE_NUMBER");//气泡号
                            node2.AppendChild(doc.CreateCDataSection(dr2["bubblenumber"].ToString()));
                            ListNode.AppendChild(node2);
                            node2 = doc.CreateElement("SELF_RESULT");//自检结果
                            node2.AppendChild(doc.CreateCDataSection(dr2["workcheckpointresultnotedis"].ToString()));
                            ListNode.AppendChild(node2);
                            ProcessNode.AppendChild(ListNode);
                        }
                    }
                }
            }

            ProcesssNode.AppendChild(ProcessNode);
            //}
            doc.AppendChild(ProcesssNode);
            return doc.InnerXml;
        }

        #endregion

        #region 新QMS理化委托调旧QMS接口
        public void RunSubmitIqsOrderByNewQmsToOldQms()
        {
            var select = @"select * from entrustmeasurement2 where nvl(issend,0)='0'";
            DataTable dt = OracleHelper.QueryTable(select, null);
            foreach (DataRow row in dt.Rows)
            {
                try
                {
                    var resQxml = row["sendxml"].ToString();
                    LogHelp.WriteLog("新QMS理化试验委托单提交集成接口-推送XML:" + resQxml);
                    NewMesToQms.unifiedFunApi mtq = new NewMesToQms.unifiedFunApi();
                    var resPxml = mtq.mesToQmsAPI(resQxml);
                    LogHelp.WriteLog("新QMS理化试验委托单提交集成接口-返回XML:" + resPxml);
                    OracleHelper.ExecuteSql(string.Format(@"update entrustmeasurement2 set resxml='{0}',issend=1 where entrustmeasurementid='{1}'", resPxml, row["entrustmeasurementid"].ToString()));
                }
                catch (Exception ex)
                {
                    LogHelp.WriteLog("新QMS理化试验委托单提交集成接口-异常:" + ex.Message);
                }
            }
        }
        #endregion

        #region 推送理化委托结果给新QMS
        public void sendIqsOrderResultToQMS()
        {
            var select = @"select * from entrustmeasurement2 en 
                where resultxml is not null
                and not exists (select 1 from writetoothersystem ws where ws.parentid=en.entrustmeasurementid and ws.recordtype='sendIqsOrderResultToQMS')";
            DataTable dt = OracleHelper.QueryTable(select, null);
            foreach (DataRow row in dt.Rows)
            {
                //调用QMS接口
                try
                {
                    string strXml = row["ResultXml"].ToString();
                    LogHelp.WriteLog("推送新QMS理化结果数据：" + strXml);
                    QISWebServices.IQIS460_MES_PRODTASK qis = new QISWebServices.IQIS460_MES_PRODTASK();
                    var result = qis.MES_TO_QIS_PROCESS(strXml);
                    LogHelp.WriteLog("推送新QMS理化结果数据-返回信息：" + result);
                    XmlDocument myxml = new XmlDocument();
                    myxml.LoadXml(result);
                    string xml = myxml.SelectSingleNode("RespMsg/document").InnerText;
                    myxml.LoadXml(xml);
                    string success = myxml.SelectSingleNode("TETTYP/RTYPE").InnerText;//
                    string message = myxml.SelectSingleNode("TETTYP/RTMSG").InnerText;//
                    //记录日志表
                    Dictionary<string, string> recordPara = new Dictionary<string, string>() { 
                         {"ParentId",row["entrustmeasurementid"].ToString()},{"RecordType","sendIqsOrderResultToQMS"},
                         {"SendXml",strXml},{"ResXml",result},{"IsSuccess",success.Equals("S")?"1":"0"},{"ContainerID",""},{"ContainerName",""},{"ProductName",""},{"WorkflowStepName",""}};
                    OracleDAL.InserOtherSystemRecord(recordPara);
                }
                catch (Exception ex)
                {
                    LogHelp.WriteLog("推送新QMS理化结果数据-异常：" + ex.Message);
                }
            }
        }
        #endregion

        #region 生产批次
        private void sendContainerInfoToQms()
        {
            var strSql = @" select cci.productname,cci.productdescription,cci.productrevision,cci.mfgordername,cci.containerid,
                cci.containername,cci.realcontainerno containerno,cci.containertype,cci.qty,w.workflowrevision,wb.workflowname,w.process_no
                --(select listagg(c.containername,',') within group(order by c.parentcontainerid) from container c where c.parentcontainerid =cci.containerid) productNo
                from containercurrentinfo cci
                left join workflow w on w.workflowid =decode(cci.isinstore,1,cci.bsworkflowid,cci.workflowid)
                left join workflowbase wb on wb.workflowbaseid =w.workflowbaseid 
                left join writetoothersystem w on w.parentid =cci.containerid and w.recordtype ='qms_container'
                where  w.parentid is null  and cci.originalstartdate>=to_date('2025-01-01','yyyy-MM-dd')
                order by cci.originalstartdate desc";
            DataTable dt = OracleHelper.QueryTable(strSql, null);
            if (dt.Rows.Count == 0) { return; }
            foreach (DataRow dr in dt.Rows)
            {
                string strXml = CreateXMLForContainer(dr);
                var result = "XSS";
                try
                {
                    //调用QMS接口
                    LogHelp.WriteLog("推送QMS生产批次数据：" + strXml);

                    LogHelp.WriteLog("推送QMS生产批次数据-返回信息：" + result);

                }
                catch (Exception ex)
                {
                    LogHelp.WriteError("推送QMS生产批次数据异常", ex);
                    result = ex.Message;
                }
                finally
                {
                    //记录日志表
                    Dictionary<string, string> recordPara = new Dictionary<string, string>() { 
                         {"ParentId",dr["containerid"].ToString()},{"RecordType","qms_container"},
                         {"SendXml",strXml},{"ResXml",result},{"IsSuccess",result.Contains("failure")?"1":"0"},{"ContainerID",dr["containerid"].ToString()},
                         {"ContainerName",dr["ContainerName"].ToString()},{"ProductName",dr["ProductName"].ToString()},{"WorkflowStepName",""}};
                    OracleDAL.InserOtherSystemRecord(recordPara);
                }
            }

        }
        private string CreateXMLForContainer(DataRow dr)
        {
            var childbatchno = string.Empty;//子序号批次
            if (dr["containertype"].ToString().Equals("3"))//批量带子序号批次 
            {
                var cbatchno = OracleHelper.GetSingle(string.Format("select listagg(c.containername,',') within group(order by c.parentcontainerid) childbatchno from container c where c.parentcontainerid ='{0}'", dr["containerid"]));
                if (cbatchno != null) { childbatchno = cbatchno.ToString(); }
            }
            XmlDocument doc = new XmlDocument();
            doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", ""));
            XmlNode ProcesssNode = doc.CreateElement("QIS_PRODs");

            XmlNode ProcessNode = doc.CreateElement("QIS_PROD");
            XmlNode node = doc.CreateElement("product_batch");//批次(大批次)
            node.AppendChild(doc.CreateCDataSection(dr["containername"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("order_no");//订单编号
            node.AppendChild(doc.CreateCDataSection(dr["mfgordername"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("product_code");//产品图号
            node.AppendChild(doc.CreateCDataSection(dr["product_code"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("product_name");//产品名称
            node.AppendChild(doc.CreateCDataSection(dr["productdescription"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("product_chart_code");//产品版本号
            node.AppendChild(doc.CreateCDataSection(dr["productrevision"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("rourion_code");//工艺编号
            node.AppendChild(doc.CreateCDataSection(dr["workflowname"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("rourion_chart_code");//工艺版本号
            node.AppendChild(doc.CreateCDataSection(dr["workflowrevision"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("product_num");//批次数量
            node.AppendChild(doc.CreateCDataSection(dr["qty"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("product_no");//子批次号，多个用逗号隔开
            node.AppendChild(doc.CreateCDataSection(childbatchno));
            ProcessNode.AppendChild(node);

            ProcesssNode.AppendChild(ProcessNode);
            doc.AppendChild(ProcesssNode);
            return doc.InnerXml;
        }
        #endregion

        #region 退料退库检验申请
        void sendStockReturnApplyDataToQMS()
        {
            DataTable dt = OracleHelper.QueryTable(@"SELECT * FROM WRITETOOTHERSYSTEM w WHERE recordtype='qms_StockReturnApply' AND nvl(ISSUCCESS,0)=0", null);
            foreach(DataRow row in dt.Rows)
            {
                var result=string.Empty;
                try
                {
                    var strXml = row["sendxml"].ToString();
                    //调用QMS接口
                    LogHelp.WriteLog("推送QMS退料退库检验申请数据：" + strXml);
                    QISWebServices.IQIS460_MES_PRODTASK qis = new QISWebServices.IQIS460_MES_PRODTASK();
                    result = qis.MES_TO_QIS_PROCESS(strXml);
                    LogHelp.WriteLog("推送QMS退料退库检验申请-返回信息：" + result);
                }
                catch (Exception ex)
                {
                    result = ex.Message;
                    LogHelp.WriteLog("推送QMS退料退库检验申请-异常：" + ex.Message);
                }
                finally 
                {
                    OracleHelper.ExecuteSql(string.Format(@"update WRITETOOTHERSYSTEM set ISSUCCESS=1,RESXML='{0}' where writetoothersystemid='{1}'", result, row["writetoothersystemid"]));
                }
            }
        }
        #endregion
    }
}
